/**
 * Created by zhouli on 2019/2/25.
 */
import React from 'react';
import {connect} from 'react-redux';
import {Input, message, Button,Checkbox,Modal} from 'antd';
import {messages, trim} from 'share/common';
import menuRoute from 'routes/menuRoute';
import "styles/login/components/try-login/try-login.scss";
import 'styles/login/login-refactoring-ui.scss'
import TryloginService from 'containers/login/components/try-login/try-login.service';
import LoginService from 'containers/login/login.service';
let timerTryLoginInterval = null;


class TryLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      src: "",//图片验证码
      verifyCode: "",//图片验证码，用户输入
      attachmentOID: "",//图片验证码
      imgLoading: false,//图片验证码是否正在加载
      username: "",//用户名
      phoneCode: "",//手机验证码
      codeTime: 61,//验证码倒数的时间
      readAgree: false,//阅读并同意
      visible: false,//汇联易协议
      verifyCodeIsPass: false,//手机与图片验证码是否通过
    }
  }

  componentWillMount() {
    this.getVerifyCodeImage();
  }
  componentDidMount() {
    this.props.onRef(this);
  }

  //输入用户名时，取消loading
  inputUsernameHandler = (evt) => {
    clearInterval(timerTryLoginInterval);
    this.setState({
      username: evt.target.value,
      loading: false,
      codeTime: 61,//验证码倒数的时间
    });
  };
  //输入图片验证码时
  inputVerifyCodeChange = (e) => {
    this.setState({
      verifyCode: e.target.value,
      loading: false,
    });
  };
  //输入手机验证码时
  enterConfirmCodeChange = (e) => {
    this.setState({
      phoneCode: e.target.value,
      loading: false,
    });
  };
  //获取验证码图片
  getVerifyCodeImage = () => {
    this.setState({
      imgLoading: true,
    });
    TryloginService.getVerifyCodeImage()
      .then(res => {
        let src = "data:image/png;base64," + res.data.image;
        this.setState({
          src: src,
          attachmentOID: res.data.attachmentOID,
          imgLoading: false,
        });
      }).catch(err => {
      this.setState({
        imgLoading: false,
      });
    })
  };
  //输完手机号点击下一步
  inputPhoneEmailNext = () => {
    const {username, attachmentOID, verifyCode} = this.state;
    if (trim(verifyCode) === "" || trim(username) === "") {
      message.warning(messages('login.key32')/*图片验证码与手机号不能为空*/);
      return;
    }
    let publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyjnL+41/pse3E0a6bM68zNnsYj2C1wEH76WY0qpIGkTWWl6DynhcV0v5S+Z4Mxj211CPBx43bcdTZoFW//sut1W68VJrJobFJxkV2mJuzreKUxqjL7FjdbAfZR5y7OAg7ueYlX5tRTIcbtb56c6KpCIz7cuEU853tgoTxUBVr1wIDAQAB";
    let params = {
      mobile: LoginService.encrypt(username, publicKey),
      verifyCode: verifyCode,
      attachmentOID: attachmentOID,
      cryptType: 3
    };
    TryloginService.sendPhoneToken(params)
      .then(res => {
        this.setState({
          loading: false,
          codeTime: 60,
        }, () => {
          timerTryLoginInterval = setInterval(() => {
            let codeTime = this.state.codeTime;
            if (codeTime > 0) {
              codeTime--;
              this.setState({
                codeTime,
              });
            }
            if (codeTime <= 0) {
              clearInterval(timerTryLoginInterval)
            }
          }, 1000);
        });
      })
      .catch(res => {
        this.getVerifyCodeImage();
        const imgCode = this.refs.imgCode;
        const  phoneNumber= this.refs.phoneNumber;
        if(res.response.data.errorCode==="FT_9001003"){
          //手机号不对
          this.setState({
            loading: false,
          },()=>{
            phoneNumber.focus();
          })
        }
        else if(res.response.data.errorCode==="FT_9001001"){
          //验证码不对
          this.setState({
            verifyCode: "",
            loading: false,
          },()=>{
            imgCode.focus();
          })
        }else {
          //验证码不对
          this.setState({
            loading: false,
          })
        }
      });
  };

  login = () => {
    const {username, phoneCode} = this.state;
    if (trim(username) === "" || trim(phoneCode) === "") {
      message.warning(messages('login.key33')/*手机号与手机验证码不能为空*/);
      return;
    }
    let params = {
      mobile: username,
      token: phoneCode
    };
    //验证码不对
    this.setState({
      loading: true,
    });
    TryloginService.bandPhoneToken(params)
      .then(res => {
        this.setState({
          loading: false,
        });
        let params = {
          username: this.state.username,
          password: undefined,
          loginType: "freeTrial",
          clientName: "",
          loginId: undefined
        };
        this.props.login(params);
      })
      .catch(()=>{
        const phoneCode = this.refs.phoneCode;
        this.setState({
          phoneCode: "",
          loading: false,
        },()=>{
          phoneCode.focus();
        })
      })
  };
  setLoading = (loading) => {
    this.setState({
      loading
    })
  };
  readAgreeChange=(e)=>{
    this.setState({readAgree: e.target.checked})
  };
  render() {
    let link = this.props.language.code.toLowerCase() === "zh_cn" ? "https://console.huilianyi.com/register/pages/protocol.html"
      : "https://console.huilianyi.com/register/pages/protocol-en.html";
    const {src, loading, codeTime,verifyCode,username,phoneCode,readAgree,visible} = this.state;
    return (
      <div className="try-login login-refactoring-ui">
        <div className="inp-wrap">
          <div className="verify-code">
            <Input size="large"
                   ref="imgCode"
                   value={verifyCode}
                   style={{border: "none"}}
                   className="verify-code-inp"
                   placeholder={messages('login.key34')/*请输入图片验证码*/}
                   onChange={this.inputVerifyCodeChange}/>
            <div className="verify-code-img">
              {src ? <img src={src}
                          onClick={this.getVerifyCodeImage}/>
                : <span onClick={this.getVerifyCodeImage}>{messages('login.key35')/*重新加载*/}</span>}
            </div>
            <div className="clear"/>
            <div className="login-refactoring-border"/>
          </div>
          <Input
            size="large"
            value={username}
            className="user-name"
            ref="phoneNumber"
            placeholder={messages('login.key36')/*请输入手机号*/}
            onChange={this.inputUsernameHandler}
          />
          <div className="verify-code2">
            <Input size="large"
                   className="verify-code-inp"
                   ref="phoneCode"
                   value={phoneCode}
                   style={{border: "none"}}
                   placeholder={messages('login.key37')/*请输入手机验证码*/}
                   onChange={this.enterConfirmCodeChange}/>
            <div className="verify-code-img">
              {codeTime === 0 ? <span className="pointer get-message-code"
                                      onClick={this.inputPhoneEmailNext}>{messages('login.key38')/*获取验证码*/}</span>
                : codeTime === 61 ? <span className="pointer get-message-code"
                                          onClick={this.inputPhoneEmailNext}>{messages('login.key38')/*获取验证码*/}</span>
                : <span className="get-message-code" style={{background: "#D2D2D2"}}>{codeTime}&nbsp;s</span>

              }
            </div>
            <div className="clear"/>
            <div className="login-refactoring-border"/>
          </div>
        </div>
        <div className="protocol-check-wrap">
          <div className="protocol-check-agree">
            &nbsp;
            <Checkbox checked={readAgree}
                      onChange={(e) => {this.readAgreeChange(e)}}/>
            &nbsp;
            <span style={{paddingLeft: 6}}>{messages('login.key57')/*阅读并同意*/}
              &nbsp;
            <span className="protocol-check-title"
                  onClick={() => {this.setState({visible: true})}}>
            {messages('login.key11'/*汇联易用户使用协议*/)}
          </span>
              </span>
          </div>
        </div>


        <Button type="primary"
                size="large"
                disabled={!(verifyCode.length && verifyCode.length &&
                  username.length && username.length &&
                  phoneCode.length && phoneCode.length) || !readAgree}
                className="login-refactoring-btn"
                onClick={this.login}
                loading={loading}> {messages('login.key39')/*立即体验*/}
        </Button>
        <Modal visible={visible}
               width={780}
               className={"protocol-modal"}
               onCancel={() => {this.setState({visible: false})}}
               footer={null}>
          <iframe src={link}
                  width={730}
                  height={450}
                  style={{border: 'none', marginTop: 30}}/>
        </Modal>
      </div>
    )
  }
}

TryLogin.propTypes = {
  login: React.PropTypes.func,//
};

TryLogin.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    tenant: state.login.tenant
  }
}

export default connect(mapStateToProps)(TryLogin);

